# 增强的工作流引擎服务
import logging
from typing import Dict, List, Any, Optional, Tuple
from django.contrib.auth.models import User, Group
from django.utils import timezone
from django.db import transaction
from datetime import datetime, timedelta
import json

from .models_workflow import WorkflowTemplate, WorkflowInstance, WorkflowStepTask, WorkflowHistory
from .notification_service import notification_service

logger = logging.getLogger(__name__)


class WorkflowEngine:
    """增强的工作流引擎"""
    
    def __init__(self):
        self.step_processors = {
            'manual': self._process_manual_step,
            'auto': self._process_auto_step,
            'notification': self._process_notification_step,
            'condition': self._process_condition_step,
            'parallel': self._process_parallel_step,
            'timer': self._process_timer_step,
            'script': self._process_script_step,
        }
    
    def create_workflow_instance(self, 
                                template_id: int, 
                                instance_name: str,
                                related_object_type: str,
                                related_object_id: int,
                                created_by: User,
                                initial_data: Dict = None) -> WorkflowInstance:
        """创建工作流实例"""
        
        try:
            template = WorkflowTemplate.objects.get(id=template_id, is_active=True)
        except WorkflowTemplate.DoesNotExist:
            raise ValueError(f"工作流模板 {template_id} 不存在或未启用")
        
        with transaction.atomic():
            instance = WorkflowInstance.objects.create(
                template=template,
                instance_name=instance_name,
                related_object_type=related_object_type,
                related_object_id=related_object_id,
                created_by=created_by,
                workflow_data=initial_data or {},
                status='pending'
            )
            
            # 记录创建历史
            WorkflowHistory.log_action(
                workflow_instance=instance,
                action='create',
                operator=created_by,
                description=f"创建工作流实例: {instance_name}"
            )
            
            return instance
            
        except Exception as e:
            logger.error(f"创建工作流实例失败: {e}")
            raise
    
    def start_workflow(self, instance_id: int, operator: User = None) -> bool:
        """启动工作流"""
        
        try:
            instance = WorkflowInstance.objects.get(id=instance_id)
            
            if instance.status != 'pending':
                raise ValueError(f"工作流状态不正确: {instance.status}")
            
            with transaction.atomic():
                instance.status = 'running'
                instance.started_at = timezone.now()
                instance.save()
                
                # 启动第一个步骤
                self._start_initial_steps(instance)
                
                # 记录启动历史
                WorkflowHistory.log_action(
                    workflow_instance=instance,
                    action='start',
                    operator=operator or instance.created_by,
                    description="启动工作流"
                )
                
                return True
                
        except Exception as e:
            logger.error(f"启动工作流失败: {e}")
            return False
    
    def _start_initial_steps(self, instance: WorkflowInstance):
        """启动初始步骤"""
        
        workflow_def = instance.template.workflow_definition
        steps = workflow_def.get('steps', [])
        
        if not steps:
            # 没有步骤，直接完成
            self._complete_workflow(instance)
            return
        
        # 找到所有起始步骤（没有前置条件的步骤）
        initial_steps = []
        for step in steps:
            if not step.get('depends_on'):
                initial_steps.append(step)
        
        if not initial_steps:
            # 如果没有明确的起始步骤，使用第一个步骤
            initial_steps = [steps[0]]
        
        # 创建初始步骤任务
        for step in initial_steps:
            self._create_step_task(instance, step)
    
    def _create_step_task(self, instance: WorkflowInstance, step_config: Dict) -> WorkflowStepTask:
        """创建步骤任务"""
        
        step_id = step_config.get('id')
        step_name = step_config.get('name', step_id)
        step_type = step_config.get('type', 'manual')
        
        # 计算截止时间
        due_date = None
        if step_config.get('timeout'):
            timeout_hours = step_config['timeout']
            due_date = timezone.now() + timedelta(hours=timeout_hours)
        
        task = WorkflowStepTask.objects.create(
            workflow_instance=instance,
            step_id=step_id,
            step_name=step_name,
            step_type=step_type,
            step_config=step_config,
            status='pending',
            due_date=due_date
        )
        
        # 分配任务
        self._assign_task(task, step_config)
        
        # 处理自动步骤
        if step_type in ['auto', 'notification', 'condition', 'script']:
            self._process_step(task)
        
        return task    
  
  def _assign_task(self, task: WorkflowStepTask, step_config: Dict):
        """分配任务"""
        
        assignee_config = step_config.get('assignee', {})
        assignee_type = assignee_config.get('type', 'user')
        
        if assignee_type == 'user':
            # 分配给特定用户
            user_id = assignee_config.get('user_id')
            if user_id:
                try:
                    user = User.objects.get(id=user_id)
                    task.assign_to(user)
                except User.DoesNotExist:
                    logger.warning(f"用户 {user_id} 不存在")
        
        elif assignee_type == 'group':
            # 分配给用户组（选择第一个可用用户）
            group_id = assignee_config.get('group_id')
            if group_id:
                try:
                    group = Group.objects.get(id=group_id)
                    users = group.user_set.filter(is_active=True)
                    if users.exists():
                        task.assign_to(users.first())
                except Group.DoesNotExist:
                    logger.warning(f"用户组 {group_id} 不存在")
        
        elif assignee_type == 'role':
            # 根据角色分配
            role = assignee_config.get('role')
            user = self._get_user_by_role(role, task.workflow_instance)
            if user:
                task.assign_to(user)
        
        elif assignee_type == 'dynamic':
            # 动态分配（基于工作流数据）
            user = self._get_dynamic_assignee(assignee_config, task.workflow_instance)
            if user:
                task.assign_to(user)
    
    def _get_user_by_role(self, role: str, instance: WorkflowInstance) -> Optional[User]:
        """根据角色获取用户"""
        
        if role == 'creator':
            return instance.created_by
        elif role == 'manager':
            # 获取创建者的上级
            creator = instance.created_by
            if hasattr(creator, 'profile') and hasattr(creator.profile, 'manager'):
                return creator.profile.manager
            # 如果没有上级，返回超级用户
            return User.objects.filter(is_superuser=True).first()
        elif role == 'admin':
            return User.objects.filter(is_superuser=True).first()
        elif role == 'department_head':
            # 获取部门负责人
            workflow_data = instance.workflow_data
            department_id = workflow_data.get('department_id')
            if department_id:
                try:
                    from .models import Department
                    department = Department.objects.get(id=department_id)
                    if hasattr(department, 'manager'):
                        return department.manager
                except:
                    pass
        
        return None
    
    def _get_dynamic_assignee(self, assignee_config: Dict, instance: WorkflowInstance) -> Optional[User]:
        """动态获取分配人"""
        
        expression = assignee_config.get('expression', '')
        workflow_data = instance.workflow_data
        
        # 简单的表达式解析
        if expression.startswith('workflow_data.'):
            field_path = expression[14:]  # 去掉 'workflow_data.' 前缀
            user_id = workflow_data.get(field_path)
            if user_id:
                try:
                    return User.objects.get(id=user_id)
                except User.DoesNotExist:
                    pass
        
        return None
    
    def _process_step(self, task: WorkflowStepTask):
        """处理步骤"""
        
        step_type = task.step_type
        processor = self.step_processors.get(step_type)
        
        if processor:
            try:
                processor(task)
            except Exception as e:
                logger.error(f"处理步骤 {task.step_id} 失败: {e}")
                task.status = 'failed'
                task.result_data = {'error': str(e)}
                task.save()
        else:
            logger.warning(f"未知的步骤类型: {step_type}")
    
    def _process_manual_step(self, task: WorkflowStepTask):
        """处理人工步骤"""
        
        # 人工步骤需要等待用户操作，发送通知
        if task.assignee:
            notification_service.send_notification(
                users=[task.assignee],
                title=f"待处理任务: {task.step_name}",
                message=f"您有一个待处理的工作流任务: {task.workflow_instance.instance_name}",
                channels=['system', 'email'],
                action_url=f"/assets/workflow/tasks/{task.id}/"
            )
    
    def _process_auto_step(self, task: WorkflowStepTask):
        """处理自动步骤"""
        
        step_config = task.step_config
        action = step_config.get('action', {})
        action_type = action.get('type')
        
        try:
            if action_type == 'update_object':
                self._execute_update_object_action(task, action)
            elif action_type == 'send_notification':
                self._execute_notification_action(task, action)
            elif action_type == 'create_record':
                self._execute_create_record_action(task, action)
            else:
                logger.warning(f"未知的自动操作类型: {action_type}")
                task.status = 'failed'
                task.save()
                return
            
            # 自动完成任务
            task.status = 'completed'
            task.completed_at = timezone.now()
            task.save()
            
            # 继续下一步
            self._check_and_continue_workflow(task.workflow_instance)
            
        except Exception as e:
            logger.error(f"执行自动步骤失败: {e}")
            task.status = 'failed'
            task.result_data = {'error': str(e)}
            task.save()
    
    def _process_notification_step(self, task: WorkflowStepTask):
        """处理通知步骤"""
        
        step_config = task.step_config
        notification_config = step_config.get('notification', {})
        
        try:
            # 获取通知接收人
            recipients = self._get_notification_recipients(notification_config, task.workflow_instance)
            
            if recipients:
                # 渲染通知内容
                title = self._render_template(notification_config.get('title', ''), task.workflow_instance.workflow_data)
                message = self._render_template(notification_config.get('message', ''), task.workflow_instance.workflow_data)
                
                # 发送通知
                notification_service.send_notification(
                    users=recipients,
                    title=title,
                    message=message,
                    channels=notification_config.get('channels', ['system'])
                )
            
            # 自动完成通知步骤
            task.status = 'completed'
            task.completed_at = timezone.now()
            task.save()
            
            # 继续下一步
            self._check_and_continue_workflow(task.workflow_instance)
            
        except Exception as e:
            logger.error(f"执行通知步骤失败: {e}")
            task.status = 'failed'
            task.result_data = {'error': str(e)}
            task.save()
    
    def _process_condition_step(self, task: WorkflowStepTask):
        """处理条件步骤"""
        
        step_config = task.step_config
        condition = step_config.get('condition', {})
        
        try:
            # 评估条件
            result = self._evaluate_condition(condition, task.workflow_instance.workflow_data)
            
            # 保存条件结果
            task.result_data = {'condition_result': result}
            task.status = 'completed'
            task.completed_at = timezone.now()
            task.save()
            
            # 根据条件结果决定下一步
            if result:
                next_steps = step_config.get('on_true', [])
            else:
                next_steps = step_config.get('on_false', [])
            
            # 创建下一步任务
            for next_step_id in next_steps:
                next_step_config = self._get_step_config_by_id(task.workflow_instance, next_step_id)
                if next_step_config:
                    self._create_step_task(task.workflow_instance, next_step_config)
            
        except Exception as e:
            logger.error(f"执行条件步骤失败: {e}")
            task.status = 'failed'
            task.result_data = {'error': str(e)}
            task.save()
    
    def _process_parallel_step(self, task: WorkflowStepTask):
        """处理并行步骤"""
        
        step_config = task.step_config
        parallel_steps = step_config.get('parallel_steps', [])
        
        try:
            # 创建所有并行步骤
            for parallel_step_config in parallel_steps:
                self._create_step_task(task.workflow_instance, parallel_step_config)
            
            # 并行步骤本身立即完成
            task.status = 'completed'
            task.completed_at = timezone.now()
            task.save()
            
        except Exception as e:
            logger.error(f"执行并行步骤失败: {e}")
            task.status = 'failed'
            task.result_data = {'error': str(e)}
            task.save()
    
    def _process_timer_step(self, task: WorkflowStepTask):
        """处理定时步骤"""
        
        step_config = task.step_config
        delay_config = step_config.get('delay', {})
        
        try:
            # 计算延迟时间
            delay_type = delay_config.get('type', 'hours')
            delay_value = delay_config.get('value', 1)
            
            if delay_type == 'hours':
                delay_time = timedelta(hours=delay_value)
            elif delay_type == 'days':
                delay_time = timedelta(days=delay_value)
            elif delay_type == 'minutes':
                delay_time = timedelta(minutes=delay_value)
            else:
                delay_time = timedelta(hours=1)  # 默认1小时
            
            # 设置任务的执行时间
            task.due_date = timezone.now() + delay_time
            task.save()
            
            # 定时任务需要通过定时器来处理，这里先标记为等待
            # 实际实现中可以使用Celery等任务队列
            
        except Exception as e:
            logger.error(f"执行定时步骤失败: {e}")
            task.status = 'failed'
            task.result_data = {'error': str(e)}
            task.save()
    
    def _process_script_step(self, task: WorkflowStepTask):
        """处理脚本步骤"""
        
        step_config = task.step_config
        script_config = step_config.get('script', {})
        
        try:
            script_type = script_config.get('type', 'python')
            script_code = script_config.get('code', '')
            
            if script_type == 'python':
                # 执行Python脚本（需要安全考虑）
                result = self._execute_python_script(script_code, task.workflow_instance.workflow_data)
                task.result_data = result
            else:
                logger.warning(f"不支持的脚本类型: {script_type}")
                task.status = 'failed'
                task.save()
                return
            
            task.status = 'completed'
            task.completed_at = timezone.now()
            task.save()
            
            # 继续下一步
            self._check_and_continue_workflow(task.workflow_instance)
            
        except Exception as e:
            logger.error(f"执行脚本步骤失败: {e}")
            task.status = 'failed'
            task.result_data = {'error': str(e)}
            task.save()
    
    def complete_manual_task(self, task_id: int, operator: User, action: str, comments: str = '', result_data: Dict = None) -> bool:
        """完成人工任务"""
        
        try:
            task = WorkflowStepTask.objects.get(id=task_id)
            
            if task.status != 'pending':
                raise ValueError(f"任务状态不正确: {task.status}")
            
            if task.assignee != operator:
                raise ValueError("只有任务分配人才能处理此任务")
            
            with transaction.atomic():
                if action == 'approve':
                    task.status = 'completed'
                    task.result_data = result_data or {'action': 'approve'}
                elif action == 'reject':
                    task.status = 'rejected'
                    task.result_data = result_data or {'action': 'reject'}
                else:
                    raise ValueError(f"无效的操作: {action}")
                
                task.completed_at = timezone.now()
                task.comments = comments
                task.save()
                
                # 记录历史
                WorkflowHistory.log_action(
                    workflow_instance=task.workflow_instance,
                    step_task=task,
                    action='step_complete' if action == 'approve' else 'step_reject',
                    operator=operator,
                    description=f"{action.title()} 步骤: {task.step_name}",
                    new_value={'action': action, 'comments': comments}
                )
                
                # 检查是否需要继续工作流
                if action == 'approve':
                    self._check_and_continue_workflow(task.workflow_instance)
                else:
                    # 拒绝可能导致工作流终止
                    self._handle_task_rejection(task)
                
                return True
                
        except Exception as e:
            logger.error(f"完成人工任务失败: {e}")
            return False    

    def _check_and_continue_workflow(self, instance: WorkflowInstance):
        """检查并继续工作流"""
        
        # 检查是否所有当前步骤都已完成
        pending_tasks = instance.step_tasks.filter(status__in=['pending', 'in_progress'])
        
        if pending_tasks.exists():
            # 还有待处理的任务，等待
            return
        
        # 检查是否有失败的任务
        failed_tasks = instance.step_tasks.filter(status='failed')
        if failed_tasks.exists():
            # 有失败的任务，终止工作流
            instance.status = 'failed'
            instance.save()
            return
        
        # 检查是否有被拒绝的任务
        rejected_tasks = instance.step_tasks.filter(status='rejected')
        if rejected_tasks.exists():
            # 有被拒绝的任务，根据配置决定是否终止
            for task in rejected_tasks:
                if task.step_config.get('reject_terminates_workflow', True):
                    instance.status = 'cancelled'
                    instance.save()
                    return
        
        # 查找下一步骤
        next_steps = self._get_next_steps(instance)
        
        if next_steps:
            # 创建下一步任务
            for step_config in next_steps:
                self._create_step_task(instance, step_config)
        else:
            # 没有下一步，完成工作流
            self._complete_workflow(instance)
    
    def _get_next_steps(self, instance: WorkflowInstance) -> List[Dict]:
        """获取下一步骤"""
        
        workflow_def = instance.template.workflow_definition
        all_steps = workflow_def.get('steps', [])
        completed_step_ids = set(instance.step_tasks.filter(status='completed').values_list('step_id', flat=True))
        
        next_steps = []
        
        for step in all_steps:
            step_id = step.get('id')
            
            # 跳过已完成的步骤
            if step_id in completed_step_ids:
                continue
            
            # 检查依赖条件
            depends_on = step.get('depends_on', [])
            if not depends_on:
                # 没有依赖，但可能已经创建过任务了
                existing_task = instance.step_tasks.filter(step_id=step_id).first()
                if not existing_task:
                    next_steps.append(step)
            else:
                # 检查所有依赖是否都已完成
                if all(dep_id in completed_step_ids for dep_id in depends_on):
                    existing_task = instance.step_tasks.filter(step_id=step_id).first()
                    if not existing_task:
                        next_steps.append(step)
        
        return next_steps
    
    def _complete_workflow(self, instance: WorkflowInstance):
        """完成工作流"""
        
        instance.status = 'completed'
        instance.completed_at = timezone.now()
        instance.save()
        
        # 执行完成后的操作
        self._execute_completion_actions(instance)
        
        # 记录完成历史
        WorkflowHistory.log_action(
            workflow_instance=instance,
            action='complete',
            operator=None,
            description="工作流完成"
        )
        
        # 发送完成通知
        notification_service.send_notification(
            users=[instance.created_by],
            title=f"工作流已完成: {instance.instance_name}",
            message=f"您的工作流 '{instance.instance_name}' 已成功完成。",
            channels=['system', 'email']
        )
    
    def _execute_completion_actions(self, instance: WorkflowInstance):
        """执行完成后的操作"""
        
        workflow_def = instance.template.workflow_definition
        completion_actions = workflow_def.get('completion_actions', {})
        
        for action_name, action_config in completion_actions.items():
            try:
                if action_name == 'update_object':
                    self._execute_update_object_action_for_instance(instance, action_config)
                elif action_name == 'send_notification':
                    self._execute_notification_action_for_instance(instance, action_config)
                elif action_name == 'create_record':
                    self._execute_create_record_action_for_instance(instance, action_config)
            except Exception as e:
                logger.error(f"执行完成操作 {action_name} 失败: {e}")
    
    def _handle_task_rejection(self, task: WorkflowStepTask):
        """处理任务拒绝"""
        
        step_config = task.step_config
        reject_config = step_config.get('on_reject', {})
        
        if reject_config.get('terminate_workflow', True):
            # 终止工作流
            task.workflow_instance.status = 'cancelled'
            task.workflow_instance.save()
            
            # 发送拒绝通知
            notification_service.send_notification(
                users=[task.workflow_instance.created_by],
                title=f"工作流被拒绝: {task.workflow_instance.instance_name}",
                message=f"您的工作流在步骤 '{task.step_name}' 被拒绝。拒绝原因: {task.comments}",
                channels=['system', 'email']
            )
        else:
            # 根据配置执行其他操作
            retry_config = reject_config.get('retry', {})
            if retry_config.get('enabled', False):
                # 重试逻辑
                self._retry_task(task, retry_config)
    
    def _retry_task(self, task: WorkflowStepTask, retry_config: Dict):
        """重试任务"""
        
        max_retries = retry_config.get('max_retries', 3)
        current_retries = task.result_data.get('retry_count', 0)
        
        if current_retries < max_retries:
            # 创建新的重试任务
            new_task = WorkflowStepTask.objects.create(
                workflow_instance=task.workflow_instance,
                step_id=task.step_id,
                step_name=f"{task.step_name} (重试 {current_retries + 1})",
                step_type=task.step_type,
                step_config=task.step_config,
                status='pending'
            )
            
            new_task.result_data = {'retry_count': current_retries + 1}
            new_task.save()
            
            # 分配任务
            self._assign_task(new_task, task.step_config)
    
    # 辅助方法
    def _render_template(self, template: str, context: Dict) -> str:
        """渲染模板字符串"""
        
        try:
            from django.template import Template, Context
            django_template = Template(template)
            return django_template.render(Context(context))
        except Exception as e:
            logger.error(f"渲染模板失败: {e}")
            return template
    
    def _evaluate_condition(self, condition: Dict, workflow_data: Dict) -> bool:
        """评估条件表达式"""
        
        condition_type = condition.get('type', 'simple')
        
        if condition_type == 'simple':
            # 简单条件: field operator value
            field = condition.get('field')
            operator = condition.get('operator')
            expected_value = condition.get('value')
            
            actual_value = workflow_data.get(field)
            
            if operator == 'equals':
                return actual_value == expected_value
            elif operator == 'not_equals':
                return actual_value != expected_value
            elif operator == 'greater_than':
                return actual_value > expected_value
            elif operator == 'less_than':
                return actual_value < expected_value
            elif operator == 'contains':
                return expected_value in str(actual_value)
            elif operator == 'exists':
                return field in workflow_data
            
        elif condition_type == 'complex':
            # 复杂条件: 支持AND/OR逻辑
            logic = condition.get('logic', 'AND')
            conditions = condition.get('conditions', [])
            
            results = [self._evaluate_condition(cond, workflow_data) for cond in conditions]
            
            if logic == 'AND':
                return all(results)
            elif logic == 'OR':
                return any(results)
        
        return False
    
    def _get_step_config_by_id(self, instance: WorkflowInstance, step_id: str) -> Optional[Dict]:
        """根据ID获取步骤配置"""
        
        workflow_def = instance.template.workflow_definition
        steps = workflow_def.get('steps', [])
        
        for step in steps:
            if step.get('id') == step_id:
                return step
        
        return None
    
    def _get_notification_recipients(self, notification_config: Dict, instance: WorkflowInstance) -> List[User]:
        """获取通知接收人"""
        
        recipients = []
        recipient_config = notification_config.get('recipients', {})
        
        if recipient_config.get('creator'):
            recipients.append(instance.created_by)
        
        if recipient_config.get('assignee'):
            # 获取当前步骤的分配人
            current_tasks = instance.step_tasks.filter(status='pending')
            for task in current_tasks:
                if task.assignee:
                    recipients.append(task.assignee)
        
        user_ids = recipient_config.get('user_ids', [])
        if user_ids:
            users = User.objects.filter(id__in=user_ids)
            recipients.extend(users)
        
        return list(set(recipients))  # 去重
    
    def _execute_update_object_action(self, task: WorkflowStepTask, action_config: Dict):
        """执行更新对象操作"""
        
        instance = task.workflow_instance
        object_type = action_config.get('object_type', instance.related_object_type)
        object_id = action_config.get('object_id', instance.related_object_id)
        updates = action_config.get('updates', {})
        
        # 根据对象类型更新对象
        if object_type == 'asset':
            from .models import Asset
            try:
                asset = Asset.objects.get(id=object_id)
                for field, value in updates.items():
                    # 支持模板变量
                    if isinstance(value, str) and value.startswith('{{') and value.endswith('}}'):
                        var_name = value[2:-2].strip()
                        value = instance.workflow_data.get(var_name, value)
                    setattr(asset, field, value)
                asset.save()
            except Asset.DoesNotExist:
                logger.error(f"资产 {object_id} 不存在")
    
    def _execute_notification_action(self, task: WorkflowStepTask, action_config: Dict):
        """执行通知操作"""
        
        recipients = self._get_notification_recipients(action_config, task.workflow_instance)
        title = self._render_template(action_config.get('title', ''), task.workflow_instance.workflow_data)
        message = self._render_template(action_config.get('message', ''), task.workflow_instance.workflow_data)
        
        notification_service.send_notification(
            users=recipients,
            title=title,
            message=message,
            channels=action_config.get('channels', ['system'])
        )
    
    def _execute_create_record_action(self, task: WorkflowStepTask, action_config: Dict):
        """执行创建记录操作"""
        
        # 这里可以根据需要创建各种记录
        # 例如创建维修记录、借用记录等
        pass
    
    def _execute_python_script(self, script_code: str, workflow_data: Dict) -> Dict:
        """执行Python脚本（安全考虑）"""
        
        # 注意：执行用户脚本存在安全风险，实际应用中需要沙箱环境
        # 这里只是示例实现
        
        try:
            # 创建受限的执行环境
            safe_globals = {
                '__builtins__': {},
                'workflow_data': workflow_data,
                'result': {}
            }
            
            # 执行脚本
            exec(script_code, safe_globals)
            
            return safe_globals.get('result', {})
            
        except Exception as e:
            logger.error(f"执行Python脚本失败: {e}")
            raise
    
    # 实例方法的包装版本
    def _execute_update_object_action_for_instance(self, instance: WorkflowInstance, action_config: Dict):
        """为实例执行更新对象操作"""
        # 创建临时任务对象用于调用通用方法
        temp_task = type('TempTask', (), {
            'workflow_instance': instance,
            'step_config': {}
        })()
        self._execute_update_object_action(temp_task, action_config)
    
    def _execute_notification_action_for_instance(self, instance: WorkflowInstance, action_config: Dict):
        """为实例执行通知操作"""
        temp_task = type('TempTask', (), {
            'workflow_instance': instance,
            'step_config': {}
        })()
        self._execute_notification_action(temp_task, action_config)
    
    def _execute_create_record_action_for_instance(self, instance: WorkflowInstance, action_config: Dict):
        """为实例执行创建记录操作"""
        temp_task = type('TempTask', (), {
            'workflow_instance': instance,
            'step_config': {}
        })()
        self._execute_create_record_action(temp_task, action_config)


# 全局工作流引擎实例
workflow_engine = WorkflowEngine()